import { Injectable } from '@nestjs/common';
import { CreateMessageDto } from './dto/create-message.dto';
import { UpdateMessageDto } from './dto/update-message.dto';
import { Repository } from 'typeorm';
import { Message } from './entities/message.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private readonly messageRepository: Repository<Message>,
  ) { }
  create(createMessageDto: CreateMessageDto) {

    return 'This action adds a new message';
  }

  findAll() {
    return `This action returns all message`;
  }
  getHello(): string {
    return 'Message Hello World!';
  }

  async getLastMessages(device_name?: string): Promise<Message[]> {
    const query = this.messageRepository
      .createQueryBuilder('message')
      .orderBy('message.id', 'DESC')
      .limit(30);

    if (device_name) {
      query.where('message.device_name = :device_name', { device_name });
    }

    return await query.getMany();
  }
  async getMessages(
    device_name?: string,
    page: number = 1,
    limit: number = 10,
  ): Promise<{ total: number; page: number; limit: number; list: Message[] }> {
    const skip = (page - 1) * limit;

    const [list, total] = await this.messageRepository.findAndCount({
      where: device_name ? { device_name } : {},
      order: { id: 'DESC' },
      skip,
      take: limit,
    });

    return {
      total,
      page,
      limit,
      list,
    };
  }

  async testConnection(): Promise<boolean> {
    console.log("测试连接数据库呢🌹")
    try {
      const count = await this.messageRepository.count();
      console.log(`Connected to the database. Total records: ${count}`);
      return true;
    } catch (error) {
      console.error('Database connection failed', error);
      return false;
    }
  }
  findOne(id: number) {
    return `This action returns a #${id} message`;
  }

  update(id: number, updateMessageDto: UpdateMessageDto) {
    return `This action updates a #${id} message`;
  }

  remove(id: number) {
    return `This action removes a #${id} message`;
  }
}
